import 'package:flutter/material.dart';

class MyListView extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return MyListViewState();
  }
}

class MyListViewState extends State<MyListView> {
  int _selectedIndex = -1;
  final List<ItemData> _data = List.generate(10, (index){
    return ItemData("index$index", false);
  });

  @override
  Widget build(BuildContext context) {

    return ListView.builder(
        itemCount: _data.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              setState(() {
                if (_selectedIndex == index) {
                  return; // 如果是选中的，则不需要处理颜色
                }
                if(_selectedIndex != -1) {
                  _data[_selectedIndex].isSelected = false; // 将之前的选择项设为默认颜色
                }

                _selectedIndex = index; // 记录新的选中项
                _data[_selectedIndex].isSelected = true; // 将新的选中项设为选中状态
              });
            },
            child: Container(
              color: _data[index].isSelected ? Colors.blue : Colors.white, // 根据是否选中来确定背景颜色
              child: Text(_data[index].data),
            ),
          );
        }
    );
  }
}

class ItemData {
  String data;
  bool isSelected;

  ItemData(this.data, this.isSelected);
}

